# encoding:utf-8
import sys 
import time
import os
from werkzeug.security import generate_password_hash
import xconfig as xconfig
from apps import config
from apps.init_app import app, mongo
from flask_script import Manager
from apscheduler.events import EVENT_JOB_EXECUTED, EVENT_JOB_ERROR
from flask_apscheduler import APScheduler
import datetime
import util.globalvar as gl

__author__ = "adog"
manager = Manager(app)
gl._init()

@manager.command
def init_site():
    pass
    
def setGlobalVariables(): 
    gl.set_value('HQ_1D', None)
    gl.set_value('FUTURE_INFO', None)
    gl.set_value('FTHQ_FI_DATA', None)
    gl.set_value('FTHQ_PIVOT_DATA', None)
    print('DATA loaded')


def aps_lister(event):
    if event.exception:
        print('%s:发生异常[%s]，可以邮件通知运维人员' % (event.job_id, event.exception))
    else:
        print('%s:运行正常' % event.job_id)


if __name__ == "__main__":

    setGlobalVariables()
    
    scheduler = APScheduler()
    scheduler.init_app(app)
    scheduler.add_job(func=setGlobalVariables, trigger='cron', hour=3, minute=30, second=0, id='setGlobalVariables')
    scheduler.add_listener(aps_lister, EVENT_JOB_EXECUTED | EVENT_JOB_ERROR)
    scheduler.start()
    
    port = xconfig.webserver_port
    if len(sys.argv) >= 2:
        if '--port=' in sys.argv[1]:
            port = int(sys.argv[1].split('=')[-1])
    app.run(host='0.0.0.0', port=xconfig.webserver_port, threaded=True)  
    
